﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EraNet.Core;
using EraNet.Core.Caching;
using EraNet.Core.Data;
using EraNet.Core.Events;
using EraNet.Core.Model.SysManage;
using EraNet.Core.Model.Account;
using EraNet.Common;
using EraNet.Common.Files;
using EraNet.Core.Model.Drivings;

namespace EraNet.Services.Drivings
{
    public class DriveSchoolService:IDriveSchoolService
    {
        #region Constants
        private const string DRIVESCHOOL_BY_ID_KEY = "Era.DriveSchool.id-{0}";
        private const string DRIVESCHOOL_PATTERN_KEY = "Era.DriveSchool.";
        private const string EMPLOYEE_BY_ID_KEY = "Era.Employee.id-{0}";
        private const string EMPLOYEE_PATTERN_KEY = "Era.Employee.";
        #endregion

        #region Fields
        private readonly IRepository<DrivingSchool> _drivingschoolRepository;
        private readonly IRepository<Employee> _employeeRepository;
        private readonly IRepository<AreaInfo> _areainfoRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        #endregion
        
        #region Ctor
        public DriveSchoolService(IRepository<DrivingSchool> drivingschoolRepository, ICacheManager cacheManager, IEventPublisher eventPublisher, IRepository<Employee> employeeRepository, IRepository<AreaInfo> areainfoRepository)
        {
            _drivingschoolRepository = drivingschoolRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
            _employeeRepository = employeeRepository;
            this._areainfoRepository = areainfoRepository;
        }
        #endregion

        #region
        public int InsertSchool(DrivingSchool model)
        {
            throw new NotImplementedException();
        }

        public int UpdateSchool(DrivingSchool model)
        {
            throw new NotImplementedException();
        }

        public IPagedList<DrivingSchool> GetSchool(string provinceMark, string cityMark, int index, int pagesize, bool showHidden = false)
        {
            throw new NotImplementedException();
        }

        public List<DrivingSchool> GetAllSchool()
        {
            var query = _drivingschoolRepository.Table.Where(c=>c.CurrentState==1);
            return query.ToList();
        }

        public List<DrivingSchool> GetSchoolByIp()
        {
            string Ipstr = Common.Request.GetIpDetails();
            //获取IP地址信息
            Core.Model.Common.AreaIp areaip = Common.JSONHelper.ParseJSON<Core.Model.Common.AreaIp>(Ipstr);
       
            var query = _drivingschoolRepository.Table.Where(c=>c.City==areaip.city&&c.CurrentState==1);
            return query.ToList();
        }

        public DrivingSchool GetSchoolById(int schoolId)
        {
            var query = _drivingschoolRepository.Table.Where(p=>p.Id==schoolId).FirstOrDefault();
            return query;
        }

        /// <summary>
        /// 获取驾校用户
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="Password"></param>
        /// <returns>0-〉登陆失败  5.登陆成功  6->用户名不存在 7-〉用户密码错误 8->用户名为空或者格式错误  9->密码为空或者格式错误 10-〉用户被锁定或者过期</returns>
        public Employee GetEmployee(string accountName, string password, out int result)
        {
            result = 0;
            #region 数据检测
            if (string.IsNullOrEmpty(accountName) || !Common.Validator.IsUserName(accountName))
            {
                result = 8;
                return null;
            }
            if (string.IsNullOrEmpty(password))
            {
                result = 9;
                return null;
            }
            #endregion
            var m = GetDrivSchoolByName(accountName);
            if (m == null)
            {
                result = 6;
            }
            else
            {
                string pwd = Utility.MD5(password);
                //string pwd = password;
                //密码错误
                if (m.Password != pwd)
                {
                    result = 7;
                    return null;
                }
                if (m.Status != 1)
                {
                    result = 10;
                    return null;
                }

                result = 5;
            }

            return m;
        }

        /// <summary>
        /// 根据用户名获取用户
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public Employee GetDrivSchoolByName(string accountName)
        {
            if (string.IsNullOrEmpty(accountName))
                return null;

            var m = _employeeRepository.Table.Where(c => c.AccountName == accountName).FirstOrDefault();
            //不存在
            if (m == null) return null;

            string key = string.Format(EMPLOYEE_BY_ID_KEY, m.Id);
            return _cacheManager.Get(key, () =>
            {
                var pv = m;
                return pv;
            });
        }



        public int DeleteSchool(int schoolId)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region
        public int InsertEmployee(Employee model)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 更新员工
        /// </summary>
        /// <param name="Member">员工实体</param>
        /// <returns>0-〉更新失败 1-〉更新成功</returns>
        public int UpdateEmployee(Employee model)
        {
            if (model == null)
                throw new ArgumentNullException("Employee");

            if (_employeeRepository.Update(model) > 0)
            {

                //cache
                _cacheManager.RemoveByPattern(EMPLOYEE_BY_ID_KEY);

                //event notification
                _eventPublisher.EntityUpdated(model);
                return 1;
            }
            return 0;
        }

        public int DeleteEmployee(int employeeId)
        {
            throw new NotImplementedException();
        }


        public Employee EmployeeLogin(string employeeAccount, string employeePwd)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取驾校实体
        /// </summary>
        /// <returns></returns>
        public Employee GetLoginClient()
        {
            Employee dsa = null;
            Object obj = null;
            if (Utility.GetCookie("DriveSchool_Member") != null && Utility.GetCookie("DriveSchool_Member") != "")
                obj = (Employee)SerializationHelper.BtyDeSerializer(Utility.GetCookie("DriveSchool_Member"));
            if (obj != null) dsa = (Employee)obj;
            return dsa;
        }
        #endregion
    }
}
